package db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.internal.win32.MEASUREITEMSTRUCT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseAdapter;

public class taodethi {

	protected Shell shell;
	private Text txtsode;
	private Text txtsocauhoi;
	private Table tabledethi;
	MessageBox ms;
	private Combo combomucdo;
	private Combo comboxemde;
    private Combo combokythi;
    private Text txttenkythi;
    private Text txtnam;
    private Text txtmakythi;
    private Combo combongay;
    private Combo combothang;
    private int tam=0;
    private Group grouptoanbo;
    private Label labelhienthi;
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			taodethi window = new taodethi();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
				
				if(tam==0){
				loadata();
				loaddecombo();
				loadkythicombo();
				tam=1;
				}
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(718, 483);
		shell.setText("tạo đề thi");
		
		 grouptoanbo = new Group(shell, SWT.NONE);
		grouptoanbo.setBounds(0, 0, 692, 142);
		
		Group group_2 = new Group(grouptoanbo, SWT.NONE);
		group_2.setBounds(0, 0, 465, 150);
		
		txtsode = new Text(group_2, SWT.BORDER);
		txtsode.setBounds(78, 73, 90, 21);
		
		 combomucdo = new Combo(group_2, SWT.NONE);
		combomucdo.setItems(new String[] {"Khó", "Trung Bình", "Dể"});
		combomucdo.setBounds(85, 112, 83, 23);
		
		Label lblNewLabel_1 = new Label(group_2, SWT.NONE);
		lblNewLabel_1.setBounds(10, 76, 62, 15);
		lblNewLabel_1.setText("Số Đề cần");
		
		Label lblNewLabel_2 = new Label(group_2, SWT.NONE);
		lblNewLabel_2.setBounds(10, 115, 73, 15);
		lblNewLabel_2.setText("Mức Độ Khó");
		
		Label lblNewLabel_3 = new Label(group_2, SWT.CENTER);
		lblNewLabel_3.setBounds(205, 48, 111, 15);
		lblNewLabel_3.setText("Số Câu Hỏi/ đề");
		
		txtsocauhoi = new Text(group_2, SWT.BORDER);
		txtsocauhoi.setBounds(227, 73, 76, 21);
		
		Button bnttao = new Button(group_2, SWT.NONE);
		bnttao.setBounds(227, 115, 89, 25);
		bnttao.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				
				if(!txtsocauhoi.getText().equals("")&&!combomucdo.getText().equals("")&&!txtsode.getText().equals(""))
				{
					if(Isnumber(txtnam.getText())&&Isnumber(txtsocauhoi.getText())&&Isnumber(txtsode.getText()))
					{
						if(checkDay(Integer.parseInt(combongay.getText()), Integer.parseInt(combothang.getText()), Integer.parseInt(txtnam.getText())))
						{
							//tao ky thi
							String ngaythangnam=txtnam.getText()+"-"+combothang.getText()+"-"+combongay.getText();
							String sql="INSERT INTO KYTHI VALUES("+"'"+txtmakythi.getText()+"'"+","+"'"+ngaythangnam+"'"+","+"'"+txttenkythi.getText()+"'"+","+null+")";
							int songchua=new Dbhandle().executeUpdate(sql);
							if(songchua==0)
							{
								ms=new MessageBox(shell);
								ms.setMessage("bạn đã nhập trùng dữ liệu");
								ms.open();
								return;
							}
							
							//end ky thi
							String str="select count(id) from cauhoi where  MUCDO="+"'"+combomucdo.getText()+"'"+"";
							String tongsocau="";
							try {
								ResultSet rs=new Dbhandle().executeQuery(str);
								while(rs.next())
								{
									tongsocau=rs.getString(1);
									
								}
							} catch (SQLException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						
							//end tong so cau hoi
							int k=0;
							for(k=0;k<Integer.parseInt(txtsode.getText());k++)
							{
								//bat dau tao danh sach  cau hoi
						      //  Random rd= new Random();
						        ArrayList<String >array =loadArrayList(Integer.parseInt(txtsocauhoi.getText()), Integer.parseInt(tongsocau));
						        int i;
						        for(i=0;i<array.size();i++)
						        {
						        	
						        	//int vt=rd.nextInt(Integer.parseInt(tongsocau));
						        	
						        	String laymacauhoi="SELECT MACAUHOI FROM CAUHOI  WHERE   MUCDO="+"'"+combomucdo.getText()+"'"+"  ORDER BY id ASC LIMIT "+array.get(i)+",1";//lay macauhoi trong cauhoi o vi tri vt
						            String macauhoi="";
						        	try {
										ResultSet rs=new Dbhandle().executeQuery(laymacauhoi);
										while(rs.next())
										{
											macauhoi=rs.getString(1);//macauhoi da duoc lay
											
										}
										
									} catch (SQLException e1) {
										// TODO Auto-generated catch block
										e1.printStackTrace();
									}
						        	
						        	//bat dau tao cau hoi cho de thi
						        	int kk=k+1;
						        	String sql1="INSERT INTO DETHI VALUES("+kk+","+"'"+txtmakythi.getText()+"'"+","+"'"+macauhoi+"'"+");";
						        	new Dbhandle().executeUpdate(sql1);
						        	
						        	
						        }
						        //ket  thuc tao danh sach cau hoi cho mot de
								
							}
							ms=new MessageBox(shell);
							ms.setMessage("bạn đã hoàn thành tạo đề thi!");
							ms.open();
							loadata();
							
							
						}else
						{
							ms=new MessageBox(shell);
							ms.setMessage("bạn hãy kiểm tra ngày tháng mà bạn nhập \n vui lòng nhập chính xác ");
							ms.open();
							
						}
						
					}
					else
					{
						ms=new MessageBox(shell);
						ms.setMessage("có những thông cần nhập là số");
						ms.open();
					}
					//tao danh sach cau hoi theo yeu cau muc do kho va so cau hoi trong de nam trong vector
					/* Random rd = new Random();
				        Vector v = new Vector();
				        int maxNumberOccur = 3;
				        int iNewNumber = 0; 
				        for (int i = 0; i < 10; i++) {
				            do{
				                iNewNumber = rd.nextInt(100);
				            }while(v.contains(iNewNumber));
				            if(!v.isEmpty()&&v.size()>=maxNumberOccur) v.remove(0);
				            v.add(iNewNumber);
				            System.out.println("Item " + (i+1) + ":" + iNewNumber);
				        }*/
					//bien chua tong so cau hoi trong bang cau hoi
					
				}
				else
				{
					ms=new MessageBox(shell);
					ms.setMessage("bạn kiểm tra xem \n có nhập đầy đủ thông tin chưa. thông tin gồm:\n số câu hỏi trong đề \n bao nhiêu đề \n  mức độ..");
					ms.open();
					return;
				}
			}
		});
		bnttao.setText("TẠo Đề Thi");
		
		Label lblNewLabel_5 = new Label(group_2, SWT.NONE);
		lblNewLabel_5.setBounds(10, 10, 62, 21);
		lblNewLabel_5.setText("tên kỳ thi");
		
		txttenkythi = new Text(group_2, SWT.BORDER);
		txttenkythi.setBounds(78, 10, 110, 21);
		
		Label lblNewLabel_6 = new Label(group_2, SWT.NONE);
		lblNewLabel_6.setBounds(195, 10, 28, 15);
		lblNewLabel_6.setText("Ngày");
		
		Label lblNewLabel_7 = new Label(group_2, SWT.NONE);
		lblNewLabel_7.setBounds(282, 10, 37, 15);
		lblNewLabel_7.setText("Tháng ");
		
		Label lblNewLabel_8 = new Label(group_2, SWT.NONE);
		lblNewLabel_8.setBounds(374, 10, 28, 15);
		lblNewLabel_8.setText("Năm");
		
		 combongay = new Combo(group_2, SWT.NONE);
		combongay.setItems(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"});
		combongay.setBounds(227, 7, 49, 23);
		
		 combothang = new Combo(group_2, SWT.NONE);
		combothang.setItems(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"});
		combothang.setBounds(322, 8, 46, 23);
		
		txtnam = new Text(group_2, SWT.BORDER);
		txtnam.setBounds(408, 7, 47, 21);
		
		Label lblNewLabel_9 = new Label(group_2, SWT.NONE);
		lblNewLabel_9.setBounds(10, 48, 55, 15);
		lblNewLabel_9.setText("mã kỳ thi");
		
		txtmakythi = new Text(group_2, SWT.BORDER);
		txtmakythi.setBounds(78, 42, 111, 21);
		
		Group group_4 = new Group(grouptoanbo, SWT.NONE);
		group_4.setBounds(471, 10, 221, 128);
		
		Button btnNewButton = new Button(group_4, SWT.NONE);
		btnNewButton.setBounds(71, 83, 75, 25);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(comboxemde.getText()!=""&& combokythi.getText()!="")
				{
					tabledethi.removeAll();
					String str="select * from dethi where made="+comboxemde.getText()+" and  MASOKYTHI="+"'"+combokythi.getText()+"'"+"";	
					try {
						ResultSet rs=new Dbhandle().executeQuery(str);
						while(rs.next())
						{
							TableItem item=new  TableItem(tabledethi, SWT.None);
							item.setText(new String []{rs.getString(1),rs.getString(2),rs.getString(3)});
							
						}
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				}
				else
				{
					ms=new MessageBox(shell);
					ms.setMessage("bạn chưa chọn đầy đủ thông tin !");
					ms.open();
					return;
				}
			
			}
		});
		btnNewButton.setText("XEM ĐỀ");
		
		Label lblNewLabel = new Label(group_4, SWT.CENTER);
		lblNewLabel.setBounds(0, 13, 80, 25);
		lblNewLabel.setText( "ĐỀ CẦN XEM");
		
		 comboxemde = new Combo(group_4, SWT.NONE);
		 comboxemde.addSelectionListener(new SelectionAdapter() {
		 	@Override
		 	public void widgetSelected(SelectionEvent e) {
		 		
		 	}
		 });
		 comboxemde.setBounds(86, 10, 55, 23);
		 
		 Label lblNewLabel_4 = new Label(group_4, SWT.CENTER);
		 lblNewLabel_4.setBounds(0, 54, 55, 23);
		 lblNewLabel_4.setText("KỲ THI");
		 
		  combokythi = new Combo(group_4, SWT.NONE);
		  combokythi.setBounds(65, 51, 101, 23);
		  
		  Button bntrefesh = new Button(group_4, SWT.NONE);
		  bntrefesh.addSelectionListener(new SelectionAdapter() {
		  	@Override
		  	public void widgetSelected(SelectionEvent e) {
		  		loaddecombo();
		  		loadkythicombo();
		  	}
		  });
		  bntrefesh.setBounds(172, 8, 39, 25);
		  bntrefesh.setText("tạo lại");
		
		Group group_1 = new Group(shell, SWT.NONE);
		group_1.setBounds(456, 397, 236, 38);
		
		Button bntEXIT = new Button(group_1, SWT.NONE);
		bntEXIT.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				System.exit(0);
			}
		});
		bntEXIT.setBounds(77, 10, 75, 25);
		bntEXIT.setText("Thoát");
		
		Group group_3 = new Group(shell, SWT.NONE);
		group_3.setBounds(0, 156, 692, 239);
		
		tabledethi = new Table(group_3, SWT.BORDER | SWT.FULL_SELECTION);
	
		tabledethi.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int i= tabledethi.getSelectionIndex();
				
				
				String laynoidungcauhoi="select noidung from cauhoi where macauhoi="+"'"+tabledethi.getItem(i).getText(2)+"'"+"";
				try {
					ResultSet rs2=new Dbhandle().executeQuery(laynoidungcauhoi);
					while(rs2.next())
					{
						
						labelhienthi.setText(rs2.getString(1));
						
						
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		
		tabledethi.addMouseTrackListener(new MouseTrackAdapter() {
			@Override
			public void mouseHover(MouseEvent e) {
				try
				{

					
					labelhienthi.setVisible(true);
					
					
				}catch(Exception e1){}
			}
			@Override
			public void mouseExit(MouseEvent e) {
				
				labelhienthi.setVisible(false);
			}
		});
		tabledethi.setBounds(0, 10, 694, 219);
		tabledethi.setHeaderVisible(true);
		tabledethi.setLinesVisible(true);
		
		TableColumn tblclmnNewColumn = new TableColumn(tabledethi, SWT.CENTER);
		tblclmnNewColumn.setWidth(133);
		tblclmnNewColumn.setText("mã số đề thi");
		
		TableColumn tblclmnNewColumn_1 = new TableColumn(tabledethi, SWT.CENTER);
		tblclmnNewColumn_1.setWidth(237);
		tblclmnNewColumn_1.setText("mã kì thi");
		
		TableColumn tblclmnNewColumn_2 = new TableColumn(tabledethi, SWT.CENTER);
		tblclmnNewColumn_2.setWidth(318);
		tblclmnNewColumn_2.setText("mã câu hỏi");
		
		 labelhienthi = new Label(shell, SWT.CENTER);
		labelhienthi.setBounds(53, 397, 359, 38);
		
		

	}
	public boolean Isnumber(String str)
	{
		try
		{
			Integer.parseInt(str);
			return true;
		}catch(Exception e)
		{
			return false;
		}
		
	}
	public boolean checkDay(int ngay,int thang,int nam)
	{

		if((thang==1||thang==3||thang==5||thang==7||thang==8||thang==10||thang==12)&&(ngay <=31&& ngay>0))
		{
			return true;
			
		}
		if((thang==4||thang==6||thang==9||thang==11)&&(ngay <=30 && ngay>0))
		{
			return true;
			
		}
		if(thang==2 )
		{
			if(nam % 100 != 0 && nam % 4 == 0)
			{
				if(ngay<=29&&ngay>0)return true;
			}
			else
			{
				if(ngay<=28&&ngay>0)return true;
			}
			
		}
		return false;
		

	
	}
	public void loadata()
	{
		
		String sql3="select * from dethi";
		try {
			ResultSet rs=new Dbhandle().executeQuery(sql3);
			
			while(rs.next())
			{
				TableItem item=new TableItem(tabledethi, SWT.None);
				item.setText(new String[]{rs.getString(1),rs.getString(2),rs.getString(3)});
				
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	public  void loaddecombo()
	{
		comboxemde.removeAll();
		String str="select DISTINCT made from dethi";
		try {
			ResultSet rs=new Dbhandle().executeQuery(str);
			
			while(rs.next())
			{
				
				comboxemde.add(rs.getString(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	public  void loadkythicombo()
	{
		combokythi.removeAll();
		String str="select DISTINCT masokythi from dethi";
		try {
			ResultSet rs1=new Dbhandle().executeQuery(str);
			
			while(rs1.next())
			{
				
				combokythi.add(rs1.getString(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	public ArrayList<String> loadArrayList(int size,int tongsocau)
	{
		Random rd=new Random();
		ArrayList<String>array=new ArrayList<String>();
		int vt=rd.nextInt(tongsocau);
		array.add(Integer.toString(vt));
		while(array.size()!=size)
		{
			
			int i;
			int tam=rd.nextInt(tongsocau);
		 for(i=0;i<array.size();i++)
		 {
			 if(Integer.parseInt(array.get(i))==tam)
				 
				 break;
			 else if(Integer.parseInt(array.get(i))!=tam && i==(array.size()-1))
			 {
				 array.add(Integer.toString(tam));
				 
			 }
			 
		 }
			
		}
		
		
		return array;
		
	}
}
